﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace PServiceBus.Ftp {
    public class Provider {

        private string _url, _username, _password;
        
        public Provider(string url, string username, string password) {
            _url = url.Replace("\\", "/");
            _username = username;
            _password = password;
            _url += _url.EndsWith("/") ? string.Empty : "/";
        }

        private void DoWork(Action<FtpWebRequest> action, string ftpAction, string destFile) {
            var reqFTP = FtpWebRequest.Create(new Uri(_url + destFile)) as FtpWebRequest;
            reqFTP.Method = ftpAction;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(_username, _password);
            action(reqFTP);
            reqFTP.Abort();
        }

        public void Upload(string data, string destFile) {
            Upload(Encoding.ASCII.GetBytes(data), destFile);
        }

        public void Upload(byte[] data, string destFile) {
            DoWork(ftp => {
                var s = ftp.GetRequestStream();
                s.Write(data, 0, data.Length);
                s.Flush();
                s.Close();
            }, WebRequestMethods.Ftp.UploadFile, destFile);
        }


    }
}
